//------------------------------------------------------------------------------
// <copyright file="SerializableKeyGestureConverter.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;

namespace DAnton.Utilities.Helpers.KeyBindings
{
    public class SerializableKeyGestureConverter : TypeConverter
    {
        #region public methods

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                string[] values = value.ToString().Split(';');
                Key key = (Key)Enum.Parse(typeof(Key), values[0]);
                ModifierKeys modifier = (ModifierKeys)Enum.Parse(typeof(ModifierKeys), values[1]);
                string ownerWindowName = values[2];
                string description = values[3];

                return new SerializableKeyGesture(key, modifier, ownerWindowName, description);
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                SerializableKeyGesture serKeyGesture = value as SerializableKeyGesture;
                return String.Format("{0};{1};{2};{3}", serKeyGesture.Key,
                                                        serKeyGesture.Modifier,
                                                        serKeyGesture.OwnerWindowName,
                                                        serKeyGesture.Description);
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }

        #endregion
    }
}
